package com.aspectj.aop.aspects;

import com.aspectj.aop.annotation.InsertLog;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * desc   : 日志AOP
 * author : chendaning
 * date   : 6/11/21
 */
/**
 * 对方法进行添加打印信息
 * 1、打印类名
 * 2、打印方法名
 * 3、打印方法参数
 * 4、打印方法返回值
 * 5、打印方法执行时间
 *
 */
@Aspect
public class InsertLogAspect extends FatherAspect{
    private final String POINTCUT = "execution(@com.aspectj.aop.annotation.InsertLog * *(..))";

    @Pointcut(POINTCUT)
    public void onInsertLogPointcut() {}

    /**
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("onInsertLogPointcut() && @annotation(insertLog)")
    public Object executeMethod(ProceedingJoinPoint joinPoint, InsertLog insertLog) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long interval = System.currentTimeMillis() - start;

        /**
         * 信息打印组装
         */
        String className = joinPoint.getSignature().getDeclaringType().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] objectsArgs = joinPoint.getArgs();
        StringBuilder builder = new StringBuilder();
        builder.append("Log\n--------------log item -----------------\n");
        builder.append("Class:").append(className).append("\n")
                .append("Method:").append(methodName).append("\n");
        builder.append("args:(");
        for (int i = 0; i < objectsArgs.length; i++) {
            Object item = objectsArgs[i];
            builder.append(item == null ? "null" : item.toString());
            if(i != objectsArgs.length - 1) {
                builder.append(",");
            }
        }
        builder.append(")").append("\n");
        builder.append("result:").append(result == null ? "void" : result.toString()).append("\n");
        builder.append("execute time:").append(interval).append("ms").append("\n");
        logger(insertLog.TAG(), builder.toString());
        return result;
    }

}